﻿using NPOI.SS.Formula.Functions;
using Serilog;
using SqlSugar;
using StackExchange.Redis;

namespace ztDataNet.Db
{
    /// <summary>
    /// 数据库配置器
    /// </summary>
    public static class SqlsugarSetup
    {
        /// <summary>
        /// 注册数据库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="dbName"></param>
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration,
        string dbName = "ConnectString")
        {
            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.MySql,
                ConnectionString = configuration[dbName],
                IsAutoCloseConnection = true,
            },
                db =>
                {
                    //单例参数配置，所有上下文生效       
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(sql);//输出sql
                    };

                    //技巧：拿到非ORM注入对象
                    //services.GetService<注入对象>();
                });
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }

    }

    /// <summary>
    /// 请求日志类
    /// </summary>
    public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        /// <summary>
        /// 请求
        /// </summary>
        /// <param name="next"></param>
        public RequestLoggingMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// 核心方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            // 记录请求参数
            context.Request.EnableBuffering();
            var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
            context.Request.Body.Position = 0; // 重置流的位置
            Serilog.Log.Information($"HTTP Request: {context.Request.Method} {context.Request.Path} Body: {requestBody}");

            // 处理请求并记录响应
            var originalBodyStream = context.Response.Body;
            using (var responseBody = new MemoryStream())
            {
                context.Response.Body = responseBody;

                await _next(context);

                responseBody.Seek(0, SeekOrigin.Begin);
                var text = await new StreamReader(responseBody).ReadToEndAsync();
                responseBody.Seek(0, SeekOrigin.Begin);

                Serilog.Log.Information($"HTTP Response: {text}");

                await responseBody.CopyToAsync(originalBodyStream);
            }
        }
        
    }
   
}